package com.jxgm.spring.boot.config;

import com.jxgm.spring.boot.Intercepto.LoginHandlerInterceptor;
import com.jxgm.spring.boot.bean.MyFilter;
import com.jxgm.spring.boot.bean.MyListener;
import com.jxgm.spring.boot.bean.MyServlet;
import org.springframework.boot.web.server.ConfigurableWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.Filter;
import java.util.Arrays;

/**
 * @author Administrator
 * @date 2020/10/14 8:22
 * @description
 **/
@Configuration
public class WebMVConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**")
                .excludePathPatterns(
                        "/","/user/to/login","/user/do/login","/static/**","/**/*.svg",
                        "/**/*.js","/**/*.css","/**/*.ico","/webjars/**");

    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {

        registry.addViewController("/").setViewName("login");
        registry.addViewController("/user/main").setViewName("main");

    }

    @Bean
    public WebServerFactoryCustomizer<ConfigurableWebServerFactory>  myWebServerFactoryCustomizer(){

        return new WebServerFactoryCustomizer<ConfigurableWebServerFactory>() {
            @Override
            public void customize(ConfigurableWebServerFactory factory) {
                factory.setPort(8001);
            }
        };
    }

    /**
     * 三大组件
     * 1.Servlet组件
     * 2.Filter组件
     * @return
     */
    @Bean
    public ServletRegistrationBean myServlet() {
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new MyServlet(), "/MyServlet");
        servletRegistrationBean.setLoadOnStartup(1);
        return servletRegistrationBean;
    }

    @Bean
    public FilterRegistrationBean myFilter(){

        FilterRegistrationBean<Filter> filterRegistrationBean = new FilterRegistrationBean<>();

        filterRegistrationBean.setFilter(new MyFilter());

        filterRegistrationBean.setUrlPatterns(Arrays.asList("/hello","/myServlet"));

        return filterRegistrationBean;

    }

    @Bean
    public ServletRegistrationBean<MyListener> myListener(){

        ServletRegistrationBean<MyListener> servletRequestListener = new ServletRegistrationBean<MyListener>();

        return servletRequestListener;

    }


}
